import java.io.File;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Vector;
import java.lang.Object;


public class Server
{
	
	static ServerSocket serverSocket = null;
	static boolean isBusy = false;
	static String directoryName = "file_dir";


	private static File dir;
	private static File[] fileList;
	static String centralServerhostName = "";
    static String rmiServer = "CentralServer";
    static String  serverPort = "";
    static CentralServerInterface centralServer = null;
    static String myHostName = "";
	public static void main(String[] args)
	{
		
		try
		{
			
			serverSocket = new ServerSocket(Integer.parseInt(args[0]));
            serverPort =  "" +serverSocket.getLocalPort();
            CentralServerInterface centralServer = null;
            directoryName += serverPort;
            centralServerhostName = args[1];
            centralServer = (CentralServerInterface) Naming.lookup ("//" + centralServerhostName + "/"+rmiServer);
            myHostName = mGetHostName();
            centralServer.mRegister(myHostName,serverPort );
            CreateDirectory();
            CheckAlive xCheckAlive = new CheckAlive(serverSocket);
            xCheckAlive.start();

			
			while(true)
			{
				
				System.out.println("Waiting ");
				Socket clientSocket = serverSocket.accept();
				HandleClient cThread = new HandleClient(clientSocket,serverSocket.getLocalPort(),myHostName);
				cThread.start();
										
			}
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
		
	private static void CreateDirectory() 
	{
		
		File xFile = new File(Server.directoryName);
		xFile.mkdir();
							
	}
	
	public static File[] GetFileList()
	{
		dir = new File(Server.directoryName);
		fileList = dir.listFiles();
		return fileList;
	}
	
	// Returns the hostname of the machine on which it is being run
	public static String mGetHostName() throws UnknownHostException
	{
		InetAddress addr = InetAddress.getLocalHost(); 
		  // Get IP Address 
		  byte[] ipAddr = addr.getAddress(); 
		  // Get hostname 
		  String hostname = addr.getHostName();
		  
		  return hostname;
	}
	
}


